# Tiltfile for FastAPI and Dapr Development

# Load extensions for Helm and nerdctl
load('ext://helm_remote', 'helm_remote')
load('ext://nerdctl', 'nerdctl_build')

# Increase apply timeout for Helm deployments
update_settings(k8s_upsert_timeout_secs=300)

# 1. Define and apply the dapr-system namespace
print("Defining dapr-system namespace YAML")
k8s_yaml(local('kubectl create namespace dapr-system --dry-run=client -o yaml'))

# 2. Install Dapr runtime via Helm
print("Deploying Dapr Core Helm chart")
helm_remote(
    chart='dapr',
    repo_url='https://dapr.github.io/helm-charts/',
    repo_name='dapr',
    version='1.15',
    release_name='dapr',
    namespace='dapr-system',
    set=['global.mtls.enabled=false'],
)

# 3. Install Dapr Dashboard via Helm
print("Deploying Dapr Dashboard Helm chart")
helm_remote(
    chart='dapr-dashboard',
    repo_url='https://dapr.github.io/helm-charts/',
    repo_name='dapr',
    release_name='dapr-dashboard',
    namespace='dapr-system'
)

# 4. Configure Dapr Dashboard port-forwarding
print("Configuring Dapr Dashboard port-forward")
k8s_resource(
    'dapr-dashboard',
    port_forwards=[port_forward(local_port=8080, container_port=8080, name='dapr-dashboard-ui')],
    labels=['dapr-ui']
)

# 5. Deploy Redis via Helm into the default namespace
print("Deploying Redis Helm chart")
helm_remote(
    chart='redis',
    repo_url='https://charts.bitnami.com/bitnami',
    repo_name='bitnami',
    release_name='redis',
    namespace='default',
    set=['auth.enabled=false']
)

# 6. Apply Dapr components (State Store, PubSub, Subscription)
k8s_yaml(['./components/redis-state.yaml', './components/redis-pubsub.yaml', './components/subscriptions.yaml'])

# 7. Build the FastAPI image using nerdctl
nerdctl_build(
    ref='dapr-fastapi-hello',
    context='.',
    dockerfile='Dockerfile',
    live_update=[
        sync('.', '/code'),
        # Optional: Restart Uvicorn if needed
        # run('pkill -f uvicorn', trigger=['./main.py'])
    ]
)

# 8. Deploy FastAPI Kubernetes manifests
k8s_yaml(['kubernetes/deployment.yaml', 'kubernetes/service.yaml'])

# 9. Define the FastAPI resource for Tilt
k8s_resource(
    'dapr-fastapi-hello',
    port_forwards='8000:8000',
    extra_pod_selectors={'app': 'dapr-fastapi-hello'}
)